package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        String MD5Password=DigestUtils.md5DigestAsHex(password.getBytes());        //MD5加密

        if (!MD5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public Integer add(EmployeeDTO employeeDTO) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(employeeDTO,emp);  //利用BeanUtils工具类的copyProperties()方法复制
        emp.setStatus(StatusConstant.ENABLE);   //默认状态:启用
        emp.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));  //默认密码

        //这些属于公共字段,已经通过AOP技术实现了自动填充,不需要放在业务代码中
        /*emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateUser(BaseContext.getCurrentId());  //获取当前线程中的局部变量
        emp.setUpdateUser(BaseContext.getCurrentId());*/
        return employeeMapper.insert(emp);
    }

    @Override
    public PageResult findAll(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        List<Employee> employeeList = employeeMapper.selectAll(employeePageQueryDTO.getName());
        Page<Employee> page = (Page<Employee>) employeeList;
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Integer modifyStatus(Long id, Integer status) {
        Employee emp = Employee.builder()
                .status(status)
                .id(id)
                .build();
        //updateTime和updateUser属于公共字段,它们的值通过AOP技术实现自动填充
        return employeeMapper.update(emp);
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.selectById(id);
    }

    @Override
    public Integer modify(EmployeeDTO employeeDTO) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(employeeDTO,emp);
        //updateTime和updateUser属于公共字段,它们的值通过AOP技术实现自动填充
        /*emp.setUpdateUser(BaseContext.getCurrentId());  //操作人id
        emp.setUpdateTime(LocalDateTime.now()); //更新时间*/
        return employeeMapper.update(emp);
    }

    @Override
    public Integer modifyPwd(PasswordEditDTO passwordEditDTO) {
        //查询用户输入的当前密码是否正确
//        Employee emp = employeeMapper.selectById(passwordEditDTO.getEmpId());     //前端没有传过来用户id
        Employee emp = employeeMapper.selectById(BaseContext.getCurrentId());
        String md5OldPwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        String md5NewPwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());

        if(!md5OldPwd.equals(emp.getPassword())){   //密码不正确
            return -1;
        }else{  //更新密码
            //updateTime和updateUser属于公共字段,它们的值通过AOP技术实现自动填充
            emp.setPassword(md5NewPwd);
            return employeeMapper.update(emp);
        }
    }
}